﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Sisocana.Models;
using Sisocana.Core.Interfaces;
using Sisocana.Core;
using Sisocana.Core.Models;
using Sisocana.Seguridad;

namespace Sisocana.Controllers
{
    public class AccountController : Controller
    {
        private ISecurity _security;
        private IUsuarioService _user;
        
        public AccountController()
            : this(new Security(),new UsuarioService())
        {
        }

        public AccountController(ISecurity security, IUsuarioService user)
        {
            _user = user;
            _security = security;
        }

        //
        // GET: /Account/
        [AdminGralAuthorize]
        public ActionResult Index()
        {
            return View(_user.GetAll());
        }

        //
        // GET: /Account/LogOn
        [Authorize]
        public ActionResult LogOn()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (_security.ValidateUser(model.UserName,
                    FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "sha1")))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult LogOnF()
        {
            // User was redirected here because of authorization section
            if (User.Identity != null && User.Identity.IsAuthenticated)
                return RedirectToAction("LogOn","Account");

            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOnF(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (_security.ValidateUser(model.UserName, 
                    FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "sha1")))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register
        [AdminGralAuthorize]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register
        [AdminGralAuthorize]
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                UsuarioModel u = new UsuarioModel();
                u.email = model.Email;
                u.nombreUsuario = model.UserName;
                u.password = FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "sha1");
                u.tipo = model.AdminGral ? "G" : "S";
                
//                try
//                {
                    _user.Add(u);
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
//                }
//                catch (Exception e)
//                {
//                    ModelState.AddModelError("", e.Message);
//                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    changePasswordSucceeded = _security.ChangePassword
                        (FormsAuthentication.HashPasswordForStoringInConfigFile(model.OldPassword, "sha1")
                        , FormsAuthentication.HashPasswordForStoringInConfigFile(model.NewPassword, "sha1")
                        , User.Identity.Name);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess
        [Authorize]
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        [AdminGralAuthorize]
        public ActionResult Edit(string name)
        {
            UsuarioModel u = _user.GetSingle(usu => usu.nombreUsuario.Trim() == name.Trim());
            if (u.tipo == "G")
                u.check = true;
            else
                u.check = false;
            u.nombreUsuario = u.nombreUsuario.Trim();
            u.email = u.email.Trim();
            u.password = u.password.Trim();
            u.tipo = u.tipo.Trim();
            return View(u);
        }

        [AdminGralAuthorize]
        [HttpPost]
        public ActionResult Edit(UsuarioModel u)
        {
            if (ModelState.IsValid)
            {
                if (u.check)
                    u.tipo = "G";
                else
                    u.tipo = "S";
                try
                {
                    _user.Update(u);
                    return RedirectToAction("Index");
                }
                catch
                {
                    ModelState.AddModelError("", "Error: the user could not be updated.");
                }
            }
            return View(u);
        }

        [AdminGralAuthorize]
        public ActionResult Delete(string name)
        {
            UsuarioModel u = _user.GetSingle(usu => usu.nombreUsuario.Trim() == name.Trim());
            if (u.tipo == "G")
                u.tipo = "General admin";
            else
                u.tipo = "Site admin";
            return View(u);
        }

        [AdminGralAuthorize]
        [HttpPost]
        public ActionResult Delete(UsuarioModel u)
        {
            try
            {
                int res = _user.deleteUser(u);
                if (res == 0)
                    return RedirectToAction("Index");
                else
                {
                    ModelState.AddModelError("", "Error: the user could not be deleted.");
                }
            }
            catch
            {
                ModelState.AddModelError("", "Error: the user could not be deleted.");
            }
            return View(u);
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
